package 链表.两数相加2;

import utils.ListNode;
import utils.Utils;

public class Solution {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = null;
        ListNode tail = null;
        int c = 0; // 进位
        while(l1 != null || l2 != null){
            int a = l1 == null ? 0 : l1.val;
            int b = l2 == null ? 0 : l2.val;
            int sum = a + b + c;

            if(res == null){
                res = tail = new ListNode(sum % 10);
            }else{
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }

            c = sum / 10;
            if(l1 != null){
                l1 = l1.next;
            }
            if(l2 != null){
                l2 = l2.next;
            }

        }
        if(c != 0){
            tail.next = new ListNode(c);
        }

        return res;
    }
    public static void main(String[] args) {
        ListNode l1 = new ListNode(3);
        ListNode l2 = new ListNode(4,l1);
        ListNode head = new ListNode(2,l2);

        ListNode ll1 = new ListNode(4);
        ListNode ll2 = new ListNode(6,ll1);
        ListNode head1 = new ListNode(5,ll2);

        ListNode res = addTwoNumbers(head,head1);

        Utils.printLinkList(res);
    }
}
